import { Button, Form, FormItem, message, Popover, Textarea } from 'ant-design-vue';
import { DynamicConditionProps } from '../types/schemas';
import { DynamicConditionAST } from '../types/node';
import { ref, Ref, toRaw } from 'vue';

export function useSavePopoverButton(
  props: DynamicConditionProps,
  emit,
  storeConditionAst: Ref<DynamicConditionAST>,
  addOption: (key: string, name: string) => void,
  saveConditionAST: (ast: DynamicConditionAST) => Promise<any>,
) {
  const visible = ref(false);

  const form = ref({
    name: undefined,
  });
  const formRef = ref();

  function reset() {
    form.value.name = undefined;
  }

  async function doSave() {
    try {
      await formRef.value.validate();
      const key = new Date().getTime() + '';
      const name = form.value.name;
      if (name) {
        addOption(key, name);
        storeConditionAst.value.key = key;
        storeConditionAst.value.name = name;
        await saveConditionAST(toRaw(storeConditionAst.value));
        message.success('保存成功');
        emit('save');
        reset();
        close();
      }
    } catch (e) {
      console.error(e);
    }
  }

  function open() {
    visible.value = true;
  }

  function close() {
    visible.value = false;
  }

  const SaveButtonPopover = () => (
    <Popover
      vModel={[visible.value, 'visible']}
      placement={'bottom'}
      trigger={'click'}
      destroyTooltipOnHide={true}
    >
      {{
        default: () => (
          <Button size={props.size} onClick={open} class={'dc-m-r-5px'} ghost type={'primary'}>
            保存
          </Button>
        ),
        content: () => (
          <Form size={props.size} model={form.value} ref={(val) => (formRef.value = val)}>
            <FormItem
              name={'name'}
              rules={[
                {
                  required: true,
                  message: '保存条件名称不能为空',
                },
              ]}
            >
              <Textarea
                placeholder={'请输入要保存的查询条件名称'}
                rows={4}
                vModel={[form.value.name, 'value']}
              ></Textarea>
            </FormItem>
            <p class={'text-center'}>
              <Button onClick={doSave} type={'primary'} size={props.size}>
                确定
              </Button>
            </p>
          </Form>
        ),
      }}
    </Popover>
  );

  return {
    SaveButtonPopover,
  };
}
